﻿using System;
using System.Collections.Generic;
using FrameWork;
using UnityEngine;

public abstract class StateSystem<T> : MonoBehaviour
{
    /// <summary>
    /// 状态机
    /// </summary>
    protected StateMachine<T> mState;

    /// <summary>
    /// 状态栈（可用于返回使用）
    /// </summary>
    protected Stack<T> mStateStack;

    private void Awake()
    {
        mState = new StateMachine<T>();
        mStateStack = new Stack<T>();

        initialize();
        initStates();
    }

    protected virtual void initialize()
    {
    }

    protected virtual void initStates()
    {
    }

    public void OnEnable()
    {
        mState.OnStart();
    }

    public virtual void Update()
    {
        mState.OnUpdate();
    }

    public void OnDisable()
    {
        mState.OnStop();
    }

    /// <summary>
    /// 切换状态
    /// </summary>
    /// <param name="state">欲切换的状态</param>
    /// <param name="saveState">是否保存上一个状态</param>
    public void ChangeState(T state, bool saveState = false)
    {
        try
        {
            if (mState.CurrentState.Equals(state))
            {
                return;
            }

            if (saveState)
            {
                mStateStack.Push(mState.CurrentState);
            }

            Debug.LogFormat("切换状态：{0} -> {1}", mState.CurrentState, state);
            mState.ChangeState(state);
        }
        catch (Exception e)
        {
            Debug.Log(e.Message);
            throw;
        }
    }

    /// <summary>
    /// 当前状态
    /// </summary>
    public T currentState
    {
        get { return mState.CurrentState; }
    }

    /// <summary>
    /// 返回到上一个保存的状态
    /// </summary>
    /// <returns></returns>
    public bool BackState()
    {
        if (mStateStack.Count == 0)
        {
            return false;
        }

        T lastState = mStateStack.Pop();
        mStateStack.Clear();
        ChangeState(lastState);
        return true;
    }
}